package com.rose.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rose.common.constant.ProductConstant;
import com.rose.common.to.SkuReductionTO;
import com.rose.common.to.SpuBoundTO;
import com.rose.common.to.es.SkuEsModel;
import com.rose.common.to.es.SkuHasStockVo;
import com.rose.common.utils.R;
import com.rose.mall.product.dao.SpuInfoDescDao;
import com.rose.mall.product.entity.*;
import com.rose.mall.product.feign.CouponFeignService;
import com.rose.mall.product.feign.SearchFeignService;
import com.rose.mall.product.feign.WareFeignService;
import com.rose.mall.product.service.*;
import com.rose.mall.product.vo.*;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rose.common.utils.PageUtils;
import com.rose.common.utils.Query;

import com.rose.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1、保存spu的基本信息 `pms_spu_info`
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2、保存spu 的描述图片 `pms_spu_info_desc`
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity desc = new SpuInfoDescEntity();
        desc.setSpuId(spuInfoEntity.getId());
        desc.setDecript(String.join(",",decript));
        this.saveSpuInfoDesc(desc);

        // 3.保存spu的图片集 `pms_spu_images`
        List<String> images = vo.getImages();
        // 给某个商品来完成
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        // 4.保存spu的规格参数 `pms_product_attr_value` 基本属性，不是销售属性
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            // 如果页面没有提交，还需要再查询一遍 这块这个数据这里就没有封装
//            AttrRespVo attrInfo = attrService.getAttrInfo(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);



        // 5、保存spu的积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds,spuBoundTO);
        spuBoundTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if (r.getCode() != 0){
            log.error("远程保存spu信息出错");
        }

        // 5、保存当前sku对应的所有sku的信息
        List<Skus> skus = vo.getSkus();

        // 5.1) sku 的基本信息 `pms_sku_info`
        if (skus != null && skus.size() != 0){
            skus.forEach(item ->{

                String defaultUrl = "";

                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1){
                        defaultUrl = image.getImgUrl();
                    }
                }



                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                // skuName;price;skuTitle;skuSubtitle; 这四个属性对拷了
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultUrl);

                skuInfoService.saveSkuInfo(skuInfoEntity);

                //自增主键
                Long skuId = skuInfoEntity.getSkuId();


                // ================保存图片==================
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    return skuImagesEntity;
                    // filter 返回true的时候就是需要，返账false就会被剔除
                }).filter(entity -> !StringUtils.isEmpty(entity.getImgUrl())).collect(Collectors.toList());
                // 5.2) 保存sku的图片信息 `pms_sku_images`
                // todo 没有图片路径的无需保存
                skuImagesService.saveBatch(imagesEntities);
                // 5.3) sku的销售属性值  `pms_sku_sale_attr_value`
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    // attrId;attrName;attrValue
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                // 5.4) sku 的优惠信息的满减信息 `gulimall_sms`

                // 操作远程服务
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                skuReductionTO.setSkuId(skuId);
                BeanUtils.copyProperties(item,skuReductionTO);
                //判断条件 满减或者打折
                if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0"))==1 ){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                    if (r1.getCode() != 0){
                        log.error("远程保存sku优惠信息出错");
                    }
                }



            });
        }




        // `sms_sku_ladder` 打折表 `sms_sku_full_reduction` 满减表 `sms_member_price` 会员价格表 `sms_spu_bounds` 商品积分表
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity){
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity desc) {
        spuInfoDescService.save(desc);
    }



    @Override
    public void up(Long spuId) {
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);

        List<Long> attrIds = baseAttrs.stream().map(attr -> attr.getAttrId()).collect(Collectors.toList());
        // 可检索的属性id集合(不是所有属性可以检索的)
        Set<Long> isSet = new HashSet<>(attrService.selectSearchAttrIds(attrIds));

//        List<SkuEsModel.Attrs> attrs = new ArrayList<>();

        List<SkuEsModel.Attrs> attrs = baseAttrs.stream().filter(item -> {
            Long attrId = item.getAttrId();
            return isSet.contains(attrId);
        }).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());
//        productAttrValueService.

        //组装数据
        List<SkuInfoEntity>  skus= skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuids = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());


        // skuId 对应 是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            // 3.1 发送远程调用 库存系统查询是否有库存
            R hasStock = wareFeignService.getSkuHasStock(skuids);
            // 构造器受保护 所以写成内部类对象
            stockMap = hasStock.getData(new TypeReference<List<SkuHasStockVo>>(){}).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            log.warn("服务调用成功" + hasStock);
        } catch (Exception e) {
            log.error("库存服务调用失败: 原因{}",e);
        }

        Map<Long, Boolean> finalStockMap = stockMap;
        //查询当前的spuid对应的所有sku的信息,品牌的名字
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);
            //skuPrice skuImage,hasStock,brandName,brandImg,catalogName
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            //todo 1发送远程调用 库存系统是否有库存
//            esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            // 4 设置库存
            if(finalStockMap == null){
                esModel.setHasStock(true);
            }else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            //todo 2查询品牌和分类的名字信息
            //热度评分
            esModel.setHotScore(0L);
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());
            CategoryEntity category= categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());
            //todo  4.查询当前sku的所有可以被用来检索的规格属性
            //设置检索属性
            esModel.setAttrs(attrs);
            return esModel;

        }).collect(Collectors.toList());

        System.out.println(upProducts.toString());
        //todo 5.将数据发送给Es保存
        R r = searchFeignService.productStatusUp(upProducts);
        if(r.getCode() == 0 ){
            //远程调用成功
            //todo 6.修改spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //远程调用失败
            //重复调用的问题  上架服务是一个远程服务；有一个重试的机制
        }

    }


    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        return getById(skuInfoService.getById(skuId).getSpuId());
    }

}